package com.example.androidpractice.adapter;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

import com.example.androidpractice.BR;
import com.example.androidpractice.R;
import com.example.androidpractice.databinding.ActivityUserItemBinding;
import com.example.androidpractice.model.User;

import java.util.List;

public class UserListLayoutAdapter extends RecyclerView.Adapter<UserListLayoutAdapter.PeopleViewHolder> {
    private List<User> people;
    private final Activity mActivity;
    public UserListLayoutAdapter(Activity activity, List<User> people) {
        mActivity = activity;
        this.people = people;
    }
    @NonNull
    @Override
    public PeopleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return PeopleViewHolder.create(LayoutInflater.from(parent.getContext()), parent, viewType);
    }

    @Override
    public void onBindViewHolder(PeopleViewHolder holder, final int position) {
        holder.bindTo(people.get(position));
        // 判断布局
        if (holder.mBinding instanceof ActivityUserItemBinding) {
            ActivityUserItemBinding item01 = (ActivityUserItemBinding) holder.mBinding;
            item01.userItemLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(mActivity, item01.getUser().toString() + "被点了！", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return people.size();
    }

    @Override
    public int getItemViewType(int position) {

        return R.layout.activity_user_item;

    }

    static class PeopleViewHolder extends RecyclerView.ViewHolder {

        ViewDataBinding mBinding;

        static PeopleViewHolder create(LayoutInflater inflater, ViewGroup parent, int type) {
            ViewDataBinding binding = DataBindingUtil.inflate(inflater, type, parent, false);
            return new PeopleViewHolder(binding);
        }

        private PeopleViewHolder(ViewDataBinding binding) {
            super(binding.getRoot());
            mBinding = binding;
        }

        void bindTo(User person) {
            mBinding.setVariable(BR.user, person);
            mBinding.executePendingBindings();
        }
    }
}
